﻿using CommonUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsForms私钥签名公钥验签
{
    public partial class Form1 : FormBase
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnSign_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtPrivateKey.Text) || string.IsNullOrWhiteSpace(txtToSignStr.Text))
                {
                    MessageBox.Show("私钥和字符串不能为空");
                    return;
                }

                //SHA256withRSA
                string fnstr = txtToSignStr.Text;//待签名字符串
                //1。转换私钥字符串为RSACryptoServiceProvider对象
                RSACryptoServiceProvider rsaP = RsaUtil.LoadPrivateKey(txtPrivateKey.Text, "PKCS8");
                byte[] data = Encoding.UTF8.GetBytes(fnstr);//待签名字符串转成byte数组，UTF8
                byte[] byteSign = rsaP.SignData(data, "SHA256");//对应JAVA的RSAwithSHA256
                string sign = Convert.ToBase64String(byteSign);//签名byte数组转为BASE64字符串

                txtSign.Text = sign;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtPubKey.Text) || string.IsNullOrWhiteSpace(txtToSignStr.Text) || string.IsNullOrWhiteSpace(txtSign.Text))
                {
                    MessageBox.Show("公钥，签名字符串，签名 不能为空");
                    return;
                }
                byte[] signature = Convert.FromBase64String(txtSign.Text);//签名值转为byte数组
                //SHA256withRSA
                string fnstr = txtToSignStr.Text;
                //1。转换私钥字符串为RSACryptoServiceProvider对象
                RSACryptoServiceProvider rsaP = RsaUtil.LoadPublicKey(txtPubKey.Text );
                byte[] data = Encoding.UTF8.GetBytes(fnstr);//待签名字符串转成byte数组，UTF8
                bool validSign = rsaP.VerifyData(data, "SHA256", signature);//对应JAVA的RSAwithSHA256

                if(validSign)
                    lblValidRst.Text = "验证签名通过："+DateTime.Now.ToString();
                else
                    lblValidRst.Text = "验证签名 不通过：" + DateTime.Now.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
